package cn.zaichi.edu.excelcommon.utils.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.zaichi.edu.excelcommon.entity.BaseImportParam;
import cn.zaichi.edu.excelcommon.entity.ImportResult;
import cn.zaichi.edu.excelcommon.entity.ImportTitleEntity;
import cn.zaichi.edu.excelcommon.handler.BaseExcelHandler;
import cn.zaichi.edu.excelcommon.process.ExcelImportDataInfo;
import cn.zaichi.edu.excelcommon.process.ProcessingExcel;
import cn.zaichi.edu.excelcommon.utils.ExcelImport;
import cn.zaichi.edu.excelcommon.utils.ImportCellValue;
import cn.zaichi.edu.excelcommon.utils.ImportTitleUtil;
import cn.zaichi.edu.excelcommon.utils.ImportWorkbookUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * 使用 map 方式导入excel 工具类
 */
public class ExcelMapImportUtil implements ExcelImport {
    //合并单元格
    List<CellRangeAddress> combineCell;
    Workbook workbook;
    BaseExcelHandler excelHandler;
    //表头
    List<ImportTitleEntity> titleEntityList;
    //最终极表头
    List<ImportTitleEntity> lastTitleList;
    //导入参数
    BaseImportParam param;

    //返回结果
    ImportResult result;

    public ExcelMapImportUtil(BaseImportParam param) throws Exception {
        try {
            this.param=param;
            //获取工作表格
            workbook = ImportWorkbookUtil.onStart(param.getFilePath(),param.getFilePass());
            //第一个sheet的合并单元格
            combineCell=ImportCellValue.getCombineCell(workbook.getSheetAt(0));
            //表头
            titleEntityList=ImportTitleUtil.readExcelTitle(workbook,combineCell,param.getTitleStarRow(),param.getTitleEndRow(),param.getStartColumn());
            lastTitleList=ImportTitleUtil.getLastTitle(titleEntityList);
            //返回结果
            result=new ImportResult(titleEntityList,new HashMap<>(),new ArrayList<>());

        } catch (IOException e) {
            throw e;
        }
    }

    @Override
    public ImportResult getResult() {
        return result;
    }

    /**
     * 导入操作
     * @param processing
     * @throws Exception
     */
    @Override
    public void importExcel(ProcessingExcel processing) throws Exception {
        ExcelImportDataInfo importDataInfo=new ExcelImportDataInfo();
        importDataInfo.setSheetCount(workbook.getNumberOfSheets());
        importDataInfo.setUuid(param.getUuid());
        for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
            List<Map<String,String>> dataMapList=new ArrayList<>();
            Sheet sheet = workbook.getSheetAt(numSheet);
            excelHandler=ImportWorkbookUtil.getExcelHandler(excelHandler,importDataInfo,sheet,param);
            for (int rowNum = param.getStartRow(); rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row hssfRow = sheet.getRow(rowNum);
                if (hssfRow == null) {
                    continue;
                }
                Map<String,String> dataMap = getValue(numSheet, sheet, rowNum, hssfRow,processing);
                excelHandler.onFinishRow(numSheet,rowNum-param.getStartRow()+1,processing);
                dataMapList.add(dataMap);
            }
            excelHandler.onFinishSheet(numSheet,processing);
            //设置返回结果
            result.getDataMap().put(sheet.getSheetName(),dataMapList);
        }
        excelHandler.onFinishExcel(processing);
    }

    private Map<String,String> getValue(int numSheet, Sheet sheet, int rowNum,Row row, ProcessingExcel processing) {
        Map<String,String> map=new HashMap<>();

        int lastCellNum = row.getLastCellNum();
        for (int col = param.getStartColumn(); col < lastCellNum; col++) {
            if(row.getCell(col)==null){
                continue;
            }
            try {
                int cellNum=col;
                ImportTitleEntity title = lastTitleList.stream().filter(e -> e.getCell() == cellNum).findFirst().orElse(null);
                //单元格值
                String cellValue = ImportCellValue.getCellValue(combineCell, sheet, rowNum, col);
                map.put(title.getName(),cellValue);
            }catch (Exception ex){
                excelHandler.onErrorCell(numSheet,rowNum,0,"发生错误",500,processing);
            }
        }

        return map;
    }
}
